import { chooseAddress ,showToast } from "./promiseFunction";
Page({
  data: {
    address: {},
    goods_list: {},
    checkedAll: false,
    totalPrice: 0,
    count: 0,
  },
  changeItem(e) {
    let { index } = e.currentTarget.dataset;

    let _goods_list = this.data.goods_list;

    let _index = _goods_list.findIndex((Item) => Item.id === index);

    _goods_list[_index].check = !_goods_list[_index].check;
    this.setCart(_goods_list);
  },
  // 全选方法
  StateCheckAll() {
    // 获取状态，购物车数据
    let { checkedAll, goods_list } = this.data;
    goods_list.forEach((Item) => (Item.check = !checkedAll));
    this.setCart(goods_list);
    this.setData({
      checkedAll: !checkedAll,
    });
  },
  // 地址选择
  async openAddress() {
    try {
      let address = await chooseAddress();
      address.address =
        address.provinceName +
        address.cityName +
        address.countyName +
        address.detailInfo;
      wx.setStorageSync("address", address);
    } catch (e) {
      console.error(e);
    }
  },
  // 地址渲染
  onShow() {
    let _res = wx.getStorageSync("address") || [];
    let _goods_list = wx.getStorageSync("cart") || [];
    this.setCart(_goods_list);
    this.setData({
      address: _res,
    });
  },
  // 修改商品数量
  changeCount(e) {
    let { index, opration } = e.currentTarget.dataset;
    let { goods_list } = this.data;
    // 根据id查找索引
    let _index = goods_list.findIndex((Item) => Item.id === index);
    if(goods_list[_index].count===1&&opration===-1){
      // 数量减少时
      wx.showModal({
        title:"是否删除",
        success:(res)=>{
            if(!res.cancel){
                goods_list.splice(_index,1)
                this.setCart(goods_list);
            }
        }
      })
    }else{
      goods_list[_index].count+=opration
      this.setCart(goods_list);
    }
    console.log("我已经运行")
  },
  // 支付方法
  async payment(){
    //
      let {address , goods_list} = this.data
      // 判断收货地址
      if(!address.userName){
         await showToast({title:"您还没有选择收货地址"})
      }
      // 判断是否有选中
      let isCheck = goods_list.length>0?goods_list.every(Item=>Item.check===true):false
      // console.log(isCheck)
      if(!isCheck){
        await showToast({title:"您还没有选中商品"})
      }
      // 路由跳转
      wx.navigateTo({
        url:"/pages/pay/payx"
      })
  },
  // 设置商品数据
  setCart(_goods_list) {
    // 商品总价格 , 数量
    let totalPrice = 0,
      count = 0,
      checkedAll = true;
    _goods_list.forEach((Item) => {
      if (Item.check === true) {
        count += Item.count;
        totalPrice += Item.goods_price * Item.count;
      } else {
        checkedAll = false;
      }
    });
    _goods_list.length === 0 ? (checkedAll = false) : "";
    this.setData({
      goods_list: _goods_list,
      checkedAll,
      totalPrice,
      count,
    });
    wx.setStorageSync("cart", _goods_list);

  },
});
